/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.model;

import java.net.MalformedURLException;
import java.net.URL;
import javax.faces.context.FacesContext;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import offset.nodes.server.controller.AttributeConstants;
import offset.nodes.server.search.model.SearchModel;

/**
 *
 * @author Walter Lütgenau
 */
public class RepositoryUtils {
    static String repositoryURL = null;

    public static Session getRepositorySession() {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        return (Session) request.getSession().getAttribute(AttributeConstants.ATT_REPOSITORY_SESSION);
    }
    
    public static RepositoryModel getRepositoryModel() {
        return new RepositoryModel(getRepositorySession());
    }
    
    public static SearchModel getSearchModel() {
        return new SearchModel(getRepositorySession());
    }

    public static void setRepositoryURL(HttpServletRequest request) throws MalformedURLException {
        if (repositoryURL != null || request == null)
            return;

        URL requestURL = new URL(request.getRequestURL().toString());
        URL repository = new URL(requestURL.getProtocol(), requestURL.getHost(), requestURL.getPort(), request.getContextPath() + request.getServletPath());
        repositoryURL = repository.toString();
    }

    public static String getRepositoryURL() {
        if (repositoryURL == null)
            return "";
        return repositoryURL;
    }

}
